/**
 * 
 */
package com.devmindset.legoframework.client.mvc.binding;

import com.smartgwt.client.core.DataClass;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.events.ItemChangedEvent;
import com.smartgwt.client.widgets.form.events.ItemChangedHandler;
import com.smartgwt.client.widgets.form.fields.FormItem;

/**
 * Extension of {@link DynamicForm} to provide form-to-model auto binding.
 * 
 * Also here to provide unique centric behaviour for all {@link SmartForm}s used in the application.
 * 
 * @author <a href="mailto:ice.penov@devmindset.com">Ice Penov</a>
 */
public class SmartForm extends DynamicForm {
  
  /**
   * Constructs a {@link DynamicForm} using the given {@link DataSource}.
   * 
   * @param ds the dataSource
   */
  public SmartForm(DataSource ds) {
    setDataSource(ds);
    setDefaults();
  }
  
  /**
   * Constructs a {@link DynamicForm} using the given {@link DataSource} and the {@link Record} to use as 
   * a source model data for this form. It also adds a form-to-model auto binding (when the form changes, 
   * the model is reflected also).
   * 
   * @param ds the {@link DataSource}
   * @param modelData the {@link Model}
   */
  public SmartForm(final DataSource ds, final Model modelData) {
    //convert to record
    final Record record = new Record();
    for (String property : modelData.getPropertyNames()) {
      record.setAttribute(property, modelData.get(property));
    }
    ds.setTestData(new DataClass[] {record});
    setDataSource(ds);
    fetchData();
    //add model auto binding
    addItemChangedHandler(new ItemChangedHandler() {
      public void onItemChanged(ItemChangedEvent event) {
        FormItem item = event.getItem();
        modelData.set(item.getName(), event.getNewValue());
      }      
    });
    setDefaults();
  }
  
  /**
   * Set default property settings for this form.
   */
  private void setDefaults() {
    setSaveOnEnter(true);
    setWidth100();
    setHeight100();
    setPadding(5);
  }

}